﻿using LJ.WebApi.Abstractions;

namespace LJ.WebApi.Mvc.Internal;


public class WebApiContext(IHttpContextAccessor httpContextAccessor) : IWebApiContext
{
    private readonly IHttpContextAccessor _httpContextAccessor = httpContextAccessor;

    public async Task<string> GetBodyAsync()
    {
        IsHttp();
        var requestBody = await new StreamReader(_httpContextAccessor.HttpContext!.Request.Body).ReadToEndAsync();
        return requestBody;
    }

    public string GetCurrentLocation()
    {
        IsHttp();

        return _httpContextAccessor.HttpContext!.Connection.RemoteIpAddress?.MapToIPv4().ToString() ?? "127.0.0.1";
    }

    public string? GetHeader(string key)
    {
        IsHttp();
        return _httpContextAccessor.HttpContext!.Request.Headers.TryGetValue(key, out var v) ? v.FirstOrDefault() : default;
    }


    private void IsHttp()
    {
        if (_httpContextAccessor.HttpContext == null)
        {
            throw new ArgumentException("current thread no http");
        }
    }
}
